package server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;

/**
 * @author liJin
 * @date 2021/1/10 21:48
 * @desc
 */
public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,HttpServlet> servletMap;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response reSponse = new Response(outputStream);

            if (servletMap.get(request.getUrl()) == null) {
                reSponse.outputHtml(request.getUrl());
            } else {
                // 动态资源servlet
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request, reSponse);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
